package com.lovezy.platform.topic.service.impl;

import com.lovezy.platform.core.base.enums.StatusEnum;
import com.lovezy.platform.core.base.query.Pager;
import com.lovezy.platform.core.base.service.MapperService;
import com.lovezy.platform.core.exception.ServiceException;
import com.lovezy.platform.topic.mapper.TopicLikeMapper;
import com.lovezy.platform.topic.model.TopicLike;
import com.lovezy.platform.topic.model.TopicLikeExample;
import com.lovezy.platform.topic.service.TopicLikeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Optional;

import static com.lovezy.platform.topic.exception.TopicExceptionEnum.TOPIC_HAS_ALREADY_LIKED;
import static com.lovezy.platform.topic.exception.TopicExceptionEnum.TOPIC_NOT_LIKED;

/**
 * 文章话题评论服务实现
 * Created by jin on 2017/12/3.
 */
@Service
public class TopicLikeServiceImpl extends MapperService<TopicLike, Integer, TopicLikeMapper> implements TopicLikeService {

    @Override
    @Transactional
    public TopicLike likeTopic(Integer topicId, String mid) {
        Optional<TopicLike> topicLike = hasLiked(topicId, mid);
        if (topicLike.isPresent()) {
            throw new ServiceException(TOPIC_HAS_ALREADY_LIKED.getErrorCode(), TOPIC_HAS_ALREADY_LIKED.getErrorMsg());
        }
        TopicLike like = new TopicLike();
        Date now = new Date();
        like.setTopicId(topicId);
        like.setCreateId(mid);
        like.setGmtCreate(now);
        like.setStatus(StatusEnum.NORMAL.value());
        mapper.insert(like);

        return like;
    }

    @Override
    public TopicLike unlikeTopic(Integer topicId, String mid) {
        TopicLike topicLike = hasLiked(topicId, mid).orElseThrow(() -> new ServiceException(TOPIC_NOT_LIKED.getErrorCode(), TOPIC_NOT_LIKED.getErrorMsg()));
        TopicLike update = new TopicLike();
        update.setLikeId(topicLike.getLikeId());
        update.setStatus(StatusEnum.DELETED.value());
        mapper.updateByPrimaryKeySelective(update);
        return topicLike;
    }

    private Optional<TopicLike> hasLiked(Integer topicId, String mid) {
        TopicLikeExample example = new TopicLikeExample();
        example.createCriteria()
                .andTopicIdEqualTo(topicId)
                .andCreateIdEqualTo(mid)
                .andStatusEqualTo(StatusEnum.NORMAL.value());
        return Pager.doSingleton(() -> mapper.selectByExample(example));
    }
}
